package com.yunzheng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yunzheng.common.BaseResult;
import com.yunzheng.constants.SystemConstants;
import com.yunzheng.dto.ChangePuserRoleDTO;
import com.yunzheng.entity.SysUser;
import com.yunzheng.entity.SysUserProjectRole;
import com.yunzheng.enums.ResultStatuesEnums;
import com.yunzheng.exception.ServiceException;
import com.yunzheng.service.SysUserProjectRoleService;
import com.yunzheng.service.SysUserService;
import com.yunzheng.vo.UserShowVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 郭思良
 * @create 2020-08-05 10:18
 */

@Slf4j
@Api(tags = "成员管理")
@RestController
@RequestMapping("/member")
public class ProjectMemberController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysUserProjectRoleService sysUserProjectRoleService;

    /**
     * 1.邀请新成员加入项目组
     *
     * /add -- roles[2]
     *
     * @param projectId 项目ID
     */
    @ApiOperation(value = "项目组成员管理：向项目中添加新成员（邀请普通成员）")
    @GetMapping("/add")
    public BaseResult addPuser(@RequestParam("projectId") String projectId, String userPhone) {
        ensureUserPhone(userPhone);
        sysUserService.addProjectUser(projectId, userPhone);
        return BaseResult.ok();
    }

    /**
     * 2.删除项目组成员
     *
     * /remove -- roles[2]
     *
     * @param projectId 项目ID
     */
    @ApiOperation(value = "项目组成员管理：（删除项目组成员）")
    @DeleteMapping("/remove")
    public BaseResult removePuser(String projectId, String userPhone) {
        // TODO: 2020/8/16 可以通过userId来删除
        ensureUserPhone(userPhone);
        String userId = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.COL_USER_PHONE, userPhone)).getUserId();
        if (userId == null){
            throw new ServiceException(ResultStatuesEnums.USER_NOT_EXIST);
        }
        sysUserProjectRoleService.remove(new QueryWrapper<SysUserProjectRole>().eq(SysUserProjectRole.COL_PROJECT_ID,projectId).
                eq(SysUserProjectRole.COL_USER_ID,userId));
        log.debug("{} 项目删除成员 {}", projectId, userId);
        return BaseResult.ok();
    }

    /**
     * 3.根据项目ID展示所负责的成员
     *
     * /show -- authc
     */
    @ApiOperation(value = "项目组成员管理：根据项目ID展示所负责成员")
    @GetMapping("/show")
    public BaseResult showPuser(String projectId) {
        return BaseResult.ok(sysUserService.showProjectUser(projectId));
    }

    /**
     * 4.修改项目组成员角色
     *
     * /change -- roles[2]
     */
    @ApiOperation(value = "项目组成员管理：修改项目组成员角色")
    @PutMapping("/change")
    public BaseResult changePuserRole(@Valid @RequestBody ChangePuserRoleDTO input){
        sysUserProjectRoleService.update(new UpdateWrapper<SysUserProjectRole>().set(SysUserProjectRole.COL_ROLE_ID,input.getRoleId()).
                eq(SysUserProjectRole.COL_USER_ID,input.getUserId()).eq(SysUserProjectRole.COL_PROJECT_ID, input.getProjectId()));
        return BaseResult.ok();
    }

    /**
     * 5.获得所有用户
     *
     * /listAll -- authc
     */
    @ApiOperation(value = "获得所有用户")
    @GetMapping("/listAll")
    public BaseResult listAllUser(){
        List<SysUser> sysUsers = sysUserService.list();
        List<UserShowVO> showList = new ArrayList<>();
        for (SysUser sysUser : sysUsers){
            UserShowVO vo = new UserShowVO();
            BeanUtils.copyProperties(sysUser, vo);
        }
        return BaseResult.ok(showList);
    }

    /**
     * 根据关键字搜索用户
     *
     * /list/key -- authc
     */
    @ApiOperation(value = "根据关键字搜索用户")
    @GetMapping("/list/key")
    public BaseResult getUserByKey(String key){
        List<SysUser> sysUsers = sysUserService.list(new QueryWrapper<SysUser>().like(SysUser.COL_USER_PHONE, key).or().
                like(SysUser.COL_REALNAME, key).or().
                like(SysUser.COL_TEAM, key).or().
                like(SysUser.COL_TYPE, key));
        List<UserShowVO> showList = new ArrayList<>();
        for (SysUser sysUser : sysUsers){
            UserShowVO vo = new UserShowVO();
            BeanUtils.copyProperties(sysUser, vo);
            showList.add(vo);
        }
        return BaseResult.ok(showList);
    }

    /**
     * 确保手机号存在
     */
    private void ensureUserPhone(String userPhone) {
        if (!java.util.regex.Pattern.matches(SystemConstants.PHONE_REGEX, userPhone)){
            throw new ServiceException(ResultStatuesEnums.PHONE_REGEX_NOT_EXIST);
        }
    }

}
